package controller

import (
	"github.com/astaxie/beego/validation"
	"github.com/gin-gonic/gin"
	"golang.org/x/crypto/bcrypt"
	"hytx_manager/form"
	"hytx_manager/models"
	"hytx_manager/pkg/setting"
	"strconv"
	"time"
)

/**
	运营商列表
 */
func OperatorsList(c *gin.Context) {
	page, _ := strconv.Atoi(c.DefaultQuery("page", "1"))
	limit, _ := strconv.Atoi(c.DefaultQuery("limit", strconv.Itoa(setting.AppSetting.PageSize)))
	data, paginate := models.OperatorsList(page, limit, c)
	render(c, gin.H{
		"paginate": paginate,
		"data":     data,
	})
}

/**
	运营商详情
 */
func OperatorsGet(c *gin.Context) {
	id := c.Query("id")
	var o models.Operators
	models.DB.Model(models.Operators{}).Where("id=?", id).First(&o)
	render(c, o)
}

/**
	运营商添加
 */
func OperatorAdd(c *gin.Context) {
	var o form.OperatorsForm
	c.ShouldBind(&o)
	valid := validation.Validation{}
	b, err := valid.Valid(&o)
	if err != nil {
		fail(c, "")
		return
	}
	if !b {
		for _, err := range valid.Errors {
			fail(c, err.Key+" "+err.Message)
			return
		}
	}
	var us models.Users
	models.DB.Table("users").Where("account=?", o.Phone).Or("phone=?",o.Phone).First(&us)
	var m1 models.ManageCenter
	models.DB.Model(models.ManageCenter{}).Where("admin_mobile_phone=?", o.Phone).First(&m1)
	var o1 models.Operators
	models.DB.Model(models.Operators{}).Where("phone=?", o.Phone).First(&o1)
	if us.Account == o.Phone || us.Phone == o.Phone || m1.AdminMobilePhone == o.Phone || o1.Phone == o.Phone{
		fail(c, "该手机号已被使用")
		return
	}
	if !models.NewSMSValidate(o.Phone).ValidateSMS(o.Code) {
		fail(c, "验证码错误或超时")
		return
	}
	//r := util.Krand(6, util.KC_RAND_KIND_ALL)
	pass, err := bcrypt.GenerateFromPassword([]byte("123456"), 10)
	oc := models.Operators{
		Title:           o.Title,
		BusinessLicense: o.BusinessLicense,
		Name:            o.Username,
		IdCard:          o.IDCard,
		IdCardFront:     o.IDCardFront,
		IdCardBack:      o.IDCardBack,
		ProvinceId:      o.Province,
		CityId:          o.City,
		AreaId:          o.Area,
		Phone:           o.Phone,
		BankCardNo:      o.BankCardNo,
		BankCardName:    o.BankCardName,
		BankName:        o.BankName,
		CreatedAt:       time.Now(),
		PlacePartnerId:  o.ManageCenter,
		RefereeName:     o.RefereeName,
		RefereePhone:    o.RefereePhone,
		AgencyFee:       o.AgencyMoney,
		Examine:1,
		ExaminedAt:time.Now(),
	}
	//var uid int
	//models.DB.Model(&models.ManageCenter{}).Select("user_id").Where("id=?", o.ManageCenter).Row().Scan(&uid)
	var ManageCenter models.ManageCenter
	err = models.DB.Model(&models.ManageCenter{}).Where("id=?", o.ManageCenter).Find(&ManageCenter).Error
	if err != nil {
		fail(c, "没有该管理")
		return
	}
	u := &models.Users{
		Account:        o.Phone,
		Phone:          o.Phone,
		Password:       string(pass),
		Type:           2,
		PlacePartnerId: ManageCenter.UserId,
	}
	if !u.Insert() {
		serverError(c)
		return
	}
	oc.UserId = u.ID
	oc.Insert()
	//发送短信
	success(c)
}

/**
	运营商编辑
 */
func OperatorEdit(c *gin.Context) {
	var o form.OperatorsForm
	c.ShouldBind(&o)
	id,_ := strconv.Atoi(c.PostForm("id"))

	oc := models.Operators{
		Title:           o.Title,
		BusinessLicense: o.BusinessLicense,
		Name:            o.Username,
		IdCard:          o.IDCard,
		IdCardFront:     o.IDCardFront,
		IdCardBack:      o.IDCardBack,
		ProvinceId:      o.Province,
		CityId:          o.City,
		AreaId:          o.Area,
		Phone:           o.Phone,
		BankCardNo:      o.BankCardNo,
		BankCardName:    o.BankCardName,
		BankName:        o.BankName,
		CreatedAt:       time.Now(),
		PlacePartnerId:  o.ManageCenter,
		RefereeName:     o.RefereeName,
		RefereePhone:    o.RefereePhone,
		AgencyFee:       o.AgencyMoney,
	}
	var oo models.Operators
	models.DB.Model(&models.Operators{}).Where("id=?", id).First(&oo)
	if o.Phone != "" && o.Phone != oo.Phone {
		var us models.Users
		models.DB.Model(&models.Users{}).Where("account=?", o.Phone).Or("phone=?",o.Phone).First(&us)
		var m1 models.ManageCenter
		models.DB.Model(models.ManageCenter{}).Where("admin_mobile_phone=?", o.Phone).First(&m1)
		var o1 models.Operators
		models.DB.Model(models.Operators{}).Where("phone=?", o.Phone).First(&o1)
		if us.Account == o.Phone || us.Phone == o.Phone || m1.AdminMobilePhone == o.Phone || o1.Phone == o.Phone{
			fail(c, "该手机号已被使用")
			return
		}
		if !models.NewSMSValidate(o.Phone).ValidateSMS(o.Code) {
			fail(c, "验证码错误或超时")
			return
		}
		//r := util.Krand(6, util.KC_RAND_KIND_ALL)
		pass, _ := bcrypt.GenerateFromPassword([]byte("123456"), 10)
		var u models.Users

		models.DB.Table("users").Where("id=?", oo.UserId).First(&u)
		u.Password = string(pass)
		u.Phone = o.Phone
		u.Account = o.Phone
		u.Update()
		//发送短信
	}
	oc.Update(id)
	success(c)
}

/**
	运营商删除
 */
func OperatorDel(c *gin.Context) {
	id := c.Query("id")
	var o models.Operators
	models.DB.Model(models.Operators{}).Where("id=?", id).First(&o)
	models.DB.Delete(&models.Operators{}, "id=?", id)
	models.DB.Delete(&models.Users{}, "id=?", o.UserId)
	success(c)
}

/**
	运营商禁启用
 */
func OperatorAble(c *gin.Context) {
	id,_ := strconv.Atoi(c.PostForm("id"))
	status, _ := strconv.Atoi(c.PostForm("state"))
	models.DB.Model(&models.Operators{}).Where("id=?", id).Update("status", status)
	u := models.GetOperatorById(id)
	models.DB.Table("users").Where("id=?", u.UserId).Update("is_enabled", status)
	success(c)
}

/**
	管理中心列表
 */
func OperatorManageCenterList(c *gin.Context) {
	var m []*struct {
		ID    int    `json:"id"`
		Title string `json:"name"`
	}
	models.DB.Model(&models.ManageCenter{}).Select("id, title").Scan(&m)
	render(c, m)
}
/**
	审核
 */
func OperatorExamine(c *gin.Context) {
	id,_ := strconv.Atoi(c.PostForm("id"))
	o := models.GetOperatorById(id)
	//r := util.Krand(6, util.KC_RAND_KIND_ALL)
	pass, _ := bcrypt.GenerateFromPassword([]byte("123456"), 10)
	p := models.GetManageCenterById(o.PlacePartnerId)
	user := &models.Users{
		Account:        o.Phone,
		Phone:          o.Phone,
		Password:       string(pass),
		Type:           2,
		PlacePartnerId: p.UserId,
	}
	user.Insert()
	o.Examine = 1
	o.ExaminedAt = time.Now()
	o.UserId = user.ID
	o.Update(id)
	success(c)
}